package com.ruoyi.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动补充插入或更新时的值
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_BY = "createBy";
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_BY = "updateBy";
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        // 在插入时填充 createBy 和 createTime
        String username = getUsername();
        this.setFieldValByName(CREATE_BY, username, metaObject);
        this.setFieldValByName(CREATE_TIME, new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 在更新时填充 updateBy 和 updateTime，无条件更新
        String username = getUsername();
        this.setFieldValByName(UPDATE_BY, username, metaObject);
        this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
    }

    private String getUsername() {
        String username;
        try {
            // username = SecurityUtils.getLoginUser() == null ? "0" : SecurityUtils.getLoginUser().getUser().getUserId().toString();
            username = SecurityUtils.getLoginUser().getUsername();
        } catch (Exception e) {
            username = "no_login";
        }
        return username;
    }
}